package db.exchange.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import db.exchange.market.ExchangeEngine;

public class SocketReader implements Runnable {

	private static final Logger LOG = LogManager.getLogger(ExchangeEngine.class
			.getName());

	private Transport transport;

	public SocketReader(Socket socket) {
		super();
		this.socket = socket;
	}

	private Socket socket;
	private ObjectInputStream in;

	@Override
	public void run() {
		try {
			in = new ObjectInputStream(socket.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
		while (true) {
			try {
				readMessage();
			} catch (IOException e) {
				String reason = "Connection is closed (by Exchange)";
				LOG.error(reason);
				transport.disconnect(reason);
				try {
					in.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
				break;
			}
		}
	}

	private void readMessage() throws IOException {
		try {
			String message = (String) in.readObject();
			LOG.info("IN : " + message);
			transport.acceptER(message);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

}
